package com.limit.aspect;

import com.limit.token.TokensLimiter;
import lombok.AllArgsConstructor;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * AOP，在方法执行前织入
 * @author hbz
 */
@Aspect
//@Component
@AllArgsConstructor
public class TokensAspect extends AbstractController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    /**
     * 第一个*代表返回类型不限
     * 第二个*代表所有类
     * 第三个*代表所有方法
     * (..) 代表参数不限
     */
    @Pointcut("execution(* *..controller..*.*(..))")
    public void logPointCut() {
        logger.debug("logPointCut");
    }

    @Before("logPointCut()")
    public void execute(JoinPoint param) throws NoSuchMethodException, ClassNotFoundException {

        /** 获取类名和方法名 **/
        String className = param.getTarget().getClass().getName();
        MethodSignature signature = (MethodSignature) param.getSignature();
        Method method = signature.getMethod();
        TokensLimiter tokensLimiter = TokensLimiter.getInstance();
        tokensLimiter.acquire(className, method);
    }

    @Override
    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
        return null;
    }
}
